import { MemberResumeProjectExpRequest } from "@/apis/endpoint/model";
import { postMyAddoreditprojectexp } from "@/apis/endpoint/my";
import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import GpVerticelLine from "@/components/GpVerticelLine";
import { pageMapper } from "@/constants/pageMap";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { dateFormat, dateUtil } from "@/utils/date";
import { navigate } from "@/utils/navigation";
import { DatetimePicker, Popup } from "@taroify/core";
import { Button, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import clsx from "clsx";
import { useEffect, useState } from "react";
import { useImmer } from "use-immer";

interface State {
  id?: number
  name?: string
  role?: string
  description?: string
  achievement?: string
  link?: string
  compName?: string
}

interface ProjectExp extends State {
  startAt?: string
  endAt?: string
}

export default function Index() {
  const [loading, setLoading] = useState(false)
  const [state, setState] = useImmer<State>({})
  const [openTime, setOpenTime] = useState(false)
  const [minWorkDate] = useState(new Date(2000, 0, 1))
  const [maxWorkDate] = useState(new Date())
  const [workAction, setWorkAction] = useState<"start"|"end"|"pending">("pending")
  const [workStartAt, setWorkStartAt] = useState<Date>()
  const [workEndAt, setWorkEndAt] = useState<Date>()
  const { eventChannel } = useNavigateEventChannel()
  useEffect(() => {
    if (eventChannel) {
      eventChannel.once("getProjectExp", (exp: ProjectExp) => {
        if (exp) {
          const { startAt, endAt, ...s } = exp
          if (startAt) setWorkStartAt(dateUtil(startAt).toDate())
          if (endAt) setWorkEndAt(dateUtil(endAt).toDate())
          setState({...state, ...s})
        }
      })
    }
  }, [])
  function triggerWorkAction(action: "start" | "end") {
    setWorkAction(action)
    setOpenTime(true)
  }
  function confirmWorkAction(date: Date) {
    workAction === "start" ? setWorkStartAt(date) : setWorkEndAt(date)
    setOpenTime(false)
    setWorkAction("pending")
  }
  function handleEditName() {
    navigate(pageMapper.fieldEdit.simple, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.name = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          navigationbarTitleText: "项目名称",
          placeholder: "请输入项目名称",
          content: state.name,
          maxContent: 50
        } as FieldEditStateSimple)
      },
    })
  }
  function handleEditRole() {
    navigate(pageMapper.fieldEdit.simple, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.role = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          navigationbarTitleText: "项目角色",
          placeholder: "在项目中担任什么角色",
          content: state.role,
          maxContent: 12
        } as FieldEditStateSimple)
      },
    })
  }
  function handleEditDesc() {
    navigate(pageMapper.fieldEdit.multiline, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.description = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          content: state.description,
          description: "简述项目内容，向HR展示您丰富的经验",
          filedName: "项目描述",
          placeholder: "1.项目概况\n2.人员分工\n3.我的责任",
        } as FieldEditState)
      },
    })
  }
  function handleEditAchievement() {
    navigate(pageMapper.fieldEdit.multiline, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.achievement = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          content: state.achievement,
          description: "简述项目成果，向HR展示您的工作能力",
          filedName: "项目业绩",
          placeholder: "1.项目收益\n2.我的贡献\n3.我的收获",
        } as FieldEditState)
      },
    })
  }
  function handleEditLink() {
    navigate(pageMapper.fieldEdit.simple, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.link = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          navigationbarTitleText: "项目链接",
          placeholder: "请输入项目URL",
          content: state.link,
          maxContent: 100
        } as FieldEditStateSimple)
      },
    })
  }
  function handleEditCompName() {
    const query = state.compName ? { name: state.compName } : null
    navigate(pageMapper.me.resume.compname, query, "navigateTo", {
      events: {
        acceptCompname(name: string) {
          setState(draft => {
            draft.compName = name
          })
        }
      }
    })
  }
  async function handleSave() {
    if (!state.name) {
      Taro.showToast({
        title: "请输入项目名称",
        icon: "none"
      })
      return
    }
    if (!state.role) {
      Taro.showToast({
        title: "请输入项目角色",
        icon: "none"
      })
      return
    }
    if (!workStartAt) {
      Taro.showToast({
        title: "请选择项目开始时间",
        icon: "none"
      })
      return
    }
    if (!workEndAt) {
      Taro.showToast({
        title: "请选择项目终止时间",
        icon: "none"
      })
      return
    }
    if (!state.description) {
      Taro.showToast({
        title: "请输入项目描述",
        icon: "none"
      })
      return
    }
    const params: MemberResumeProjectExpRequest = {
      name: state.name,
      position: state.role,
      startTime: dateFormat(workStartAt, "short"),
      endTime: dateFormat(workEndAt, "short"),
      content: state.description,
      performance: state.achievement,
      link: state.link,
      company: state.compName,
      id: state.id
    }
    try {
      setLoading(true)
      await postMyAddoreditprojectexp(params).send()
      Taro.showToast({
        title: (params.id ? "修改" : "新增") + "成功",
        icon: "success"
      })
      navigate()
    } catch (error) {
      setLoading(false)
    }
  }
  function renderActionPannels() {
    return (
      <View>
        { renderWorkRange() }
      </View>
    )
  }
  function renderWorkRange() {
    return (
      <Popup open={openTime} rounded placement="bottom" onClose={setOpenTime}>
        <Popup.Backdrop />
        <DatetimePicker
          type="year-month"
          min={minWorkDate}
          max={maxWorkDate}
          defaultValue={workAction === "start" ? workStartAt : workEndAt}
          key={workAction}
          onConfirm={confirmWorkAction}
        >
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button type="cancel">取消</DatetimePicker.Button>
            <DatetimePicker.Title>{workAction === "start" ? "开始时间" : "结束时间"}</DatetimePicker.Title>
            <DatetimePicker.Button type="confirm">确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>
    )
  }
  return (
    <GpContainer className="bg-white">
      <View className="px-[32px] box-border pt-[16px]">
        <View className="text-[48px] font-bold text-primary">项目经验</View>
        <View className="text-[28px] mt-[28px] text-primary">优质的项目经验有助于让HR更了解您的工作能力</View>
      </View>
      <View className="px-[32px] pb-[48px]">
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">项目名称</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditName}>
            <View className={clsx("text-[32px] truncate", state.name ? "text-primary font-bold" : "text-placeholder")}>
              {state.name || "请填写项目名称"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">项目角色</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditRole}>
            <View className={clsx("text-[32px] truncate", state.role ? "text-primary font-bold" : "text-placeholder")}>
              {state.role || "请输入项目角色"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">项目时长</View>
          <View className="flex flex-row justify-between items-center gap-[24px] mt-[32px]">
            <View onClick={() => triggerWorkAction('start')} className={clsx("text-[32px] flex-1", workStartAt ? "text-primary font-bold" : "text-placeholder")}>
              {workStartAt ? dateFormat(workStartAt, "YYYY/MM") : "开始时间"}
            </View>
            <GpVerticelLine width={20} height={2} color="#313337" />
            <View onClick={() => triggerWorkAction('end')} className={clsx("text-[32px] flex-1", workEndAt ? "text-primary font-bold" : "text-placeholder")}>
              {workEndAt ? dateFormat(workEndAt, "YYYY/MM") : "结束时间"}
            </View>
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">项目描述</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditDesc}>
            <View className={clsx("text-[32px] truncate", state.description ? "text-primary font-bold" : "text-placeholder")}>
              {state.description || "请输入项目内容"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
      </View>
      <View className="w-full h-[24px] bg-[#F4F6FC]"></View>
      <View className="px-[32px] py-[48px]">
        <View className="text-secondary text-[28px]">以下为选填项</View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">项目业绩</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditAchievement}>
            <View className={clsx("text-[32px] truncate", state.achievement ? "text-primary font-bold" : "text-placeholder")}>
              {state.achievement || "请输入项目业绩（填选）"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">项目链接</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditLink}>
            <View className={clsx("text-[32px] truncate", state.link ? "text-primary font-bold" : "text-placeholder")}>
              {state.link || "请输入项目URL（填选）"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">公司名称</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditCompName}>
            <View className={clsx("text-[32px] truncate", state.compName ? "text-primary font-bold" : "text-placeholder")}>
              {state.compName || "请输入项目所属公司（填选）"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <Button className="h-[80px] mt-[80px] rounded-[64px] bg-theme text-white flex flex-row justify-center items-center text-[32px]" loading={loading} onClick={handleSave}>
          保存
        </Button>
      </View>
      { renderActionPannels() }
    </GpContainer>
  )
}
